#include <stdio.h>
#include "wifi.h"
#include "esp_wifi.h"
#include "esp_log.h"
#include "string.h"

#define TAG "WIFI"
#define WIFI_RETRY_COUNT 5

typedef enum {
    WIFI_DISCONNECTED,
    WIFI_CONNECTING,
    WIFI_CONNECTED,
} wifi_status_t;

// wifi 连接状态
uint8_t wifi_status = WIFI_DISCONNECTED;

void wifi_init(const char* ssid, const char* password)
{
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    esp_err_t ret = esp_wifi_init(&cfg);
    if (ret != ESP_OK)
    {
        ESP_LOGE("WIFI", "WiFi init failed");
        return;
    }

    
    wifi_config_t wifi_config = {0};
    strcpy((char*)wifi_config.sta.ssid, ssid);
    strcpy((char*)wifi_config.sta.password, password);
    ret = esp_wifi_set_mode(WIFI_MODE_STA);
    if (ret != ESP_OK)
    {
        ESP_LOGE("WIFI", "WiFi set mode failed");
        return;
    }

    ret = esp_wifi_set_config(WIFI_IF_STA, &wifi_config);
    if (ret != ESP_OK)
    {
        ESP_LOGE("WIFI", "WiFi set config failed");
        return;
    }

    ret = esp_wifi_start();
    if (ret != ESP_OK)
    {
        ESP_LOGE("WIFI", "WiFi start failed");
        return;
    }

    
}


void wifi_connect(void)
{
    static uint8_t current_retry_count = 0;
    current_retry_count++;
    wifi_status = WIFI_CONNECTING;
    esp_err_t ret = esp_wifi_connect();
    if (ret != ESP_OK)
    {
        ESP_LOGE("WIFI", "WiFi connect failed");
        vTaskDelay(pdMS_TO_TICKS(500));
        if(current_retry_count < WIFI_RETRY_COUNT)
        {
            wifi_connect();
        }
        wifi_status = WIFI_DISCONNECTED;
    } else {
        ESP_LOGI("WIFI", "WiFi connect success");
        wifi_status = WIFI_CONNECTED;
    }
}